var userDao = require('../dao/user.js');
var check = require('../middlewares/check.js');
module.exports = function (app) {

	app.get('/user/info',check.checkLogin,function (req,res) {
		res.render('user/info');
	});

	app.post('/user/info',check.checkLogin,function (req,res) {
		var params = req.body;
		var user = userDao.getNullUser();
		user._id = req.session.user._id;
		user.name = params.name;
		user.gender = params.gender;
		user.introduction = params.introduction;
		user.birthday = Date.parse(params.birthday);
		user.habits = params.habits.split(',');
		user.icon = params.icon;
		userDao.updateUserInfo(user,function (isSuccess,u) {
			if(isSuccess){
				req.session.user = u;
				res.redirect('/');
			}else{
				res.send("<script type='text/javascript'>alert('网络错误,请稍后再试!');history.back(-1);</script>");
			}
		});
	});

	app.get('/user/login',function (req,res) {
		res.render('user/login');
	});

	app.post('/user/login',function (req,res) {
		userDao.login(req.body,function (isSuccess,err,users) {
			if(!isSuccess){
				res.send("<script type='text/javascript'>alert('登录失败,请稍后再试!');history.back(-1);</script>");
			}else{
				if(users.length == 1){
					var u = users[0];
					req.session.user = u;
					res.redirect('/');
				}else {
					res.send("<script type='text/javascript'>alert('用户名或密码错误!');history.back(-1);</script>");
				}
			}
		});
	});

	app.get('/user/register',function (req,res) {
		res.render('user/register');
	});

	app.post('/user/register',function (req,res) {
		userDao.checkUserName(req.body.userName,function (isAble,message) {
			if(!isAble){
				res.send("<script type='text/javascript'>alert('用户名不可用!');history.back(-1);</script>");
			}else{
				userDao.register(req.body,function (isSuccess,err,user) {
					if(isSuccess){
						res.redirect('/user/login');
					}else{
						console.log(err);
						res.send("<script type='text/javascript'>alert('注册失败,请稍后再试!');history.back(-1);</script>");
					}
				});
			}
		});
	});

	app.get('/user/logout',function (req,res) {
		delete req.session.user;
		res.locals.user = null;
		res.redirect('/');
	});

	app.post('/user/check',function (req,res) {
		var name = req.body.name;
		console.log(req.body);
		userDao.checkUserName(name,function (isAble,message) {
			res.json({
				status:isAble,
				message:message
			});
		});
	});
};